package com.junlinpro.controller;


import java.nio.charset.Charset;

import org.mortbay.log.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.junlinpro.entity.CardInfo;
import com.junlinpro.service.RealTimeAudioService;
import com.junlinpro.utils.CardStateUtil;
import com.junlinpro.utils.PcmInByteData;
import com.junlinpro.utils.SocketChannelMap;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("realtime")
public class RealTimeAudioController {
	
    @Autowired
    private RealTimeAudioService realTimeAudioService;

    @Autowired
    private PcmInByteData pcmInByteData;
    
    @Autowired
    private CardStateUtil cardStateUtil;
    
    protected HttpHeaders httpHeaders = new HttpHeaders();   

    
    public RealTimeAudioController() {
    	MediaType mediaType = new MediaType("text", "html", Charset.forName("UTF-8"));
        httpHeaders.setContentType(mediaType);
    }

    @PostMapping(value = "/start")
    public ResponseEntity<String> startRealtimeAudio(@RequestBody CardInfo card) {
    	log.info("start开启实时监听接口被调用");
    	JSONObject result = new JSONObject();
    	result.put("code", 201);
    	result.put("data", 2);
    	result.put("msg", "开启实时监听接口调用失败");
    	
    	String cardId = String.valueOf(card.getCardId());
    	
        try {           
            
            if(SocketChannelMap.monitorTaskMapGet(cardId)==null) {            
	            String wavKey = card.getCardId() + "_" + card.getChannelId();
	            // 在新开启一个监听的时候先根据key删除数据，预防有残留数据
	            pcmInByteData.removePcmData(wavKey);
	            Channel channel = SocketChannelMap.get(cardId);
	            if (channel != null) {        
	                // 储存下发状态，收到嵌入式的开始监听回复后才将状态设置为true
	                SocketChannelMap.taskMapPut(SocketChannelMap.startTaskKey + cardId, false);
	                // 调用下发命令线程
	                realTimeAudioService.startCmd(channel, cardId, card.getChannelId() + "", 1);
	                result.put("code", 200);
	            	result.put("data", 1);
	            	result.put("msg", "接口调用成功，开始下发开启实时监听指令，如果采集卡不响应会持续下发1分钟");
	            }else {
	            	result.put("msg", "接口调用成功，开始下发开启实时监听指令，但找不到对应的通道");
	            	log.info("下发开启实时监听指令，但找不到对应的通道");
	            }
            }else {
            	result.put("msg", "接口调用成功，该卡已在监听，无需重复下发开启实时监听指令");
            	log.info(cardId+"已在实时监听，无需重复下发开启实时监听指令");
            }
            
            
        	
        } catch (Exception e) {
        	Log.info("实时监听开启接口Exception:"+e.getMessage());
            e.printStackTrace();            
        }catch(Error  e) {
        	Log.info("实时监听开启接口 Error:"+e.getMessage());
        	e.printStackTrace();
        	
        }
        return new ResponseEntity<String>(result.toJSONString(), httpHeaders, HttpStatus.OK);
    }

    @PostMapping(value = "/stop")
    public ResponseEntity<String> stopRealtimeAudio(@RequestBody CardInfo card) {
    	log.info("stop结束实时监听接口被调用");
    	JSONObject result = new JSONObject();
    	result.put("code", 201);
    	result.put("data", 2);
    	result.put("msg", "stop结束实时监听接口调用失败");
    	
    	String cardId = String.valueOf(card.getCardId());
        try {
            Channel channel = SocketChannelMap.get(cardId);
            
            //在监听则下发停止命令
            if(   (SocketChannelMap.monitorTaskMapGet(cardId)!=null && SocketChannelMap.monitorTaskMapGet(cardId)) 
                ||(cardStateUtil.cardStateGet(String.valueOf(cardId))!=null )){
	            String wavKey = card.getCardId() + "_" + card.getChannelId();
	            if (channel != null) {
	                // 储存下发状态，收到嵌入式的开始监听回复后才将状态设置为true
	                SocketChannelMap.taskMapPut(SocketChannelMap.stopTaskKey + cardId, false);
	                // 调用下发命令线程
	                realTimeAudioService.startCmd(channel, cardId, card.getChannelId() + "", 2);
	                result.put("code", 200);
	            	result.put("data", 1);
	            	result.put("msg", "stop结束实时监听接口调用成功，开始下发停止实时监听指令，如果采集卡不响应会持续下发1分钟\"");
	            }else {
	            	result.put("msg", "接口调用成功，开始下发停止实时监听指令，但找不到对应的通道");
	            	log.info(wavKey+"下发实时监听结束指令，但找不到对应的通道");
	            }
            }else {
            	result.put("msg", "接口调用成功，但没有开启实时监听，无需下发停止实时监听指令");
            	log.info(cardId+"没有开启实时监听，无需下发实时监听结束指令");
            }
            
            
        	
        } catch (Exception e) {        	
        	Log.info("结束实时监听接口Exception:"+e.getMessage());
            e.printStackTrace();            
        }
        
        return new ResponseEntity<String>(result.toJSONString(), httpHeaders, HttpStatus.OK);
    }
    
  
}
